import { FolderClose } from '@icon-park/react'
import useCategory from '@renderer/hooks/useCategory/index'
import { useStore } from '@renderer/store/useStore'
import classNames from 'classnames'
import { NavLink, useFetcher } from 'react-router-dom'
import styles from './index.module.scss'
interface Props {
  category: CategoryType
}
export default function CategoryItem({ category }: Props) {
  const { contextMenu, dragHandle } = useCategory(category)
  const fetcher = useFetcher() //使用fethcer的submit不会刷新路由，而useSubmit会刷新
  const editCategoryId = useStore((state) => state.editCategoryId)
  const setEditCategoryId = useStore((state) => state.setEditCategoryId)

  return (
    <>
      {editCategoryId === category.id ? (
        <div className={styles.input}>
          <input
            defaultValue={category.name}
            name="name"
            autoFocus
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                fetcher.submit(
                  { action: 'update', id: category.id, name: e.currentTarget.value },
                  { method: 'PUT' },
                )
                setEditCategoryId(0)
              }
            }}
          ></input>
        </div>
      ) : (
        <NavLink
          to={`/config/category/contentList/${category.id}`}
          className={({ isActive }) => classNames(styles.link, isActive ? styles.active : '')}
          key={category.id}
          onDoubleClick={() => setEditCategoryId(category.id)}
          onContextMenu={contextMenu()}
          {...dragHandle}
        >
          <div className="flex items-center gap-1">
            <FolderClose theme="outline" size="12" strokeWidth={3}></FolderClose>
            <div className="truncate">{category.name}</div>
          </div>
        </NavLink>
      )}
    </>
  )
}
